package bookmark

import (
	"encoding/json"
	"os"

	"code.google.com/awwwe-browser/auralvm/param"
	"code.google.com/awwwe-browser/data"
	"code.google.com/awwwe-browser/slurp"
)

// a bookmark slice
type SliceBookmark struct {
	data.SlicerBase
}

// a cmp method for bookmarks
func cmpBookmark(i1 interface{}, i2 interface{}) int {
	if i1.(Bookmark).Key == i2.(Bookmark).Key {
		return 0
	}
	if i1.(Bookmark).Title > i2.(Bookmark).Title {
		return 1
	} else {
		return -1
	}
}

// Builds a bookmark slice.
// Param length is the start length of the array's slice
// Param capacity is the size of the slice's array
//
// example:
//  var ss SliceBookmark
//  ss = BuildSliceBookmark(0, 5)
func BuildSliceBookmark(length, capacity int) SliceBookmark {
	var v SliceBookmark
	v.Init(length, capacity, cmpBookmark)
	return v
}

// Appends a slice of bookmarks to the slice.
// Param src is the slice of bookmarks to be appended.
func (this *SliceBookmark) AppendSlice(src []Bookmark) {
	var v Bookmark
	for _, v = range src {
		this.Append(&v)
	}
}

// AtIndex returns the bookmark at the index.
func (this *SliceBookmark) AtIndex(index int) *Bookmark {
    var ifc interface{}
    ifc = this.SlicerBase.AtIndex(index)
    if ifc != nil {
	    return ifc.(*Bookmark)
    }
    return nil
}

// Remove gets a bookmark at index
// Deletes the bookmark at index form the array
// Returns the bookmark.
func (this *SliceBookmark) Remove(index int) *Bookmark {
	var ifc interface{}
	ifc = this.SlicerBase.Remove(index)
    if ifc != nil {
		return ifc.(*Bookmark)    
    }
    return nil
}

// Slice returns the data as a slice of bookmarks.
func (this *SliceBookmark) Slice() []*Bookmark {
	var i, length int
	var item interface{}
	var ss []*Bookmark
	length = len(this.Data)
	ss = make([]*Bookmark, length, length)
	for i, item = range this.Data {
		ss[i] = item.(*Bookmark)
	}
	return ss
}

// Save saves the data to the bookmarks file.
func (this *SliceBookmark) Save() error {
	var markup []byte
	var err error
	var file *os.File
	markup, err = json.MarshalIndent(this.Slice(), "", "  ")
	if err == nil {
		file, err = os.Create(param.LocalBookmarkFilePath)
		defer file.Close()
		if err == nil {
			_, err = file.Write(markup)
		}
	}
	return err
}

// GetBookmarks reads the bookmarks from the file and returns a SliceBookmark.
func GetBookmarks() SliceBookmark {
	var slicebm SliceBookmark
	var bmbm []Bookmark
	var markup []byte
	var err error
	bmbm = make([]Bookmark, 0, 5)
	slicebm = BuildSliceBookmark(0, 20)
	markup, err = slurp.SlurpFile(param.LocalBookmarkFilePath)
	if err == nil {
		err = json.Unmarshal(markup, &bmbm)
		if err == nil {
			slicebm.AppendSlice(bmbm)
		}
	}
	return slicebm
}
